package com.neulogistics.contrib.procuredcenter.api.application.query;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neulogistics.contrib.procuredcenter.api.application.converter.PurchaseOrderPOVMConverter;
import com.neulogistics.contrib.procuredcenter.api.application.converter.PurchaseOrderQueryPOConverter;
import com.neulogistics.contrib.procuredcenter.api.application.viewmodel.PurchaseOrderViewModel;
import com.neulogistics.contrib.procuredcenter.infrastructure.persistence.orm.po.PurchaseOrderPO;
import com.neulogistics.contrib.procuredcenter.infrastructure.persistence.orm.service.IPurchaseOrderPOService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PurchaseOrderQueryService implements IPurchaseOrderQueryService {
    @Resource
    IPurchaseOrderPOService purchaseOrderPOService;

    @Override
    public PurchaseOrderViewModel getById(Integer purchaseOrderId) {
        PurchaseOrderPO purchaseOrderPO = purchaseOrderPOService.getById(purchaseOrderId);
        PurchaseOrderViewModel purchaseOrderViewModel = PurchaseOrderPOVMConverter.POToVM(purchaseOrderPO);
        return purchaseOrderViewModel;
    }

    @Override
    public Page<PurchaseOrderViewModel> page(PurchaseOrderQuery purchaseOrderQuery) {
        // 取出条件
        PurchaseOrderPO goodsPOQuery = PurchaseOrderQueryPOConverter.queryToPO(purchaseOrderQuery);
        long current = purchaseOrderQuery.getPageNum();
        long pageSize = purchaseOrderQuery.getPageSize();

        // 查询
        QueryWrapper<PurchaseOrderPO> queryWrapper = new QueryWrapper<>(goodsPOQuery);
        Page<PurchaseOrderPO> page = purchaseOrderPOService.page(new Page<>(current, pageSize), queryWrapper);

        // 构造结果
        Page<PurchaseOrderViewModel> viewModelPage = new Page<>(current, pageSize);
        List<PurchaseOrderViewModel> viewModelList = page.getRecords().stream()
                .map(PurchaseOrderPOVMConverter::POToVM).collect(Collectors.toList());
        viewModelPage.setRecords(viewModelList);
        viewModelPage.setTotal(page.getTotal());

        return viewModelPage;
    }
}
